import express from 'express';
const router = express.Router();
import { NotFoundError, UploadError, ValidationError } from '../utils/errors';
import { formatResponse } from '../utils/tool';
import fileUpload from 'express-fileupload';
import { uploadService, queryFilesByConditonService } from '../service/loadService';
import { deleteFileByMD5Dao, queryFileByMD5Dao } from '../dao/loadDao';

router.post('/', fileUpload({}), async function(req, res, next) {
  const fileUploaded = await uploadService(req.files)
  res.send(formatResponse(0, '上传成功', fileUploaded))
})
// 分页查询
router.get('/', async function(req, res, next) {
  const files = await queryFilesByConditonService(req.query)
  res.send(formatResponse(0, '', files))
})

router.get('/:md5', async function(req, res, next) {
  const file = await queryFileByMD5Dao(req.params.md5)
  if (file.length === 0) {
    throw new NotFoundError()
  }
  const { mimetype, data_buffer } = file[0];
  // 设置响应头信息
  res.setHeader('Content-Type', mimetype);
  res.send(data_buffer)
})

router.delete('/:md5', async function(req, res, next) {
  await deleteFileByMD5Dao(req.params.md5)
  res.send(formatResponse(0, '删除成功', null))
})

export default router;